import { Card, Form, Input, Checkbox, Button, message } from 'antd'
import logo from '@/assets/logo.png'
// 导入样式文件
import './index.scss'
import { useStore } from '@/store'
import { useNavigate } from 'react-router-dom'
const Login = () => {
  const { loginStore } = useStore()
  const navigate = useNavigate()
  const onFinish = async ({ mobile, code }) => {
    // values放置的是所有表单项中用户输入的内容
    try {
      await loginStore.getToken({ mobile, code })
      // 跳转首页
      navigate('/', { replace: true })
      // 提示用户
      message.success('登录成功')
    } catch (e) {
      message.error(e.response?.data?.message || '登录失败')
    }

  }

  // 校验失败的提交数据
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        {/* 子项用到的触发事件 需要在Form中声明一下才可以 */}
        <Form
          initialValues={{ remember: true, code: '246810' }}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', validateTrigger: 'onBlur' },
            ]}>
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
            ]}>
            <Input size="large" placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked">
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>

          <Form.Item>
            {/*  渲染Button组件为submit按钮  */}
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login